export default class ObjectUtils {

    public static deepClone(obj, newObj?: any) {
        var newObj = newObj || ((obj.constructor === Array) ? [] : {});
        for (let key in obj) {
            if (typeof obj[key] == 'object') {
                newObj[key] = (obj[key].constructor === Array) ? [] : {}
                this.deepClone(obj[key], newObj[key]);
            } else {
                newObj[key] = obj[key]
            }
        }
        return newObj;
    }

    public static deepAssign(target, sources) {
        for (const key in sources) {
            if (Object.prototype.hasOwnProperty.call(sources, key)) {
                const element = sources[key];
                if (!element) {
                    target[key] = element;
                } else if (typeof element == 'object') {
                    if (!target[key]) {
                        target[key] = (element.constructor === Array) ? [] : {}
                    }
                    this.deepAssign(target[key], element)
                } else {
                    target[key] = element;
                }
            }
        }
    }
    
    public static deepCopy(obj): any {
        // 判断是否是对象
        if (typeof obj !== 'object') return;
        // 判断obj类型，根据类型新建一个对象或者数组
        let newObj = obj instanceof Array ? [] : {}
        // 遍历对象，进行赋值
        for (let key in obj) {
            if (obj.hasOwnProperty(key)) {
                let val = obj[key];
                // 判断属性值的类型，如果是对象，递归调用deepCopy
                newObj[key] = typeof val === 'object' ? this.deepCopy(val) : val
            }
        }
        return newObj
    }
}